package com.example.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2020/11/17 18:45
 * @description: TODO   impala   数据源 配置 lalala
 * @version: V1.0 1212121
 * @slogan: 天下风云出我辈，一入代码岁月催
 */
@Configuration
@MapperScan(basePackages = "com.example.dao.impala.**", sqlSessionTemplateRef = "impalaSqlSessionTemplate")
public class ImpalaDatasourceConfig {

    @Bean(name = "impalaDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.impala")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "impalaSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("impalaDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //设置数据源
        bean.setDataSource(dataSource);
        //设置mybatis映射路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mappers/impala/**/**.xml"));
        return bean.getObject();
    }

    @Bean(name = "impalaSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("impalaSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 配置事务管理，如果使用到事务需要注入该 Bean，否则事务不会生效
     * 在需要的地方加上 @Transactional 注解即可
     */
/*
    @Bean(name = "impalaDataSourceTransactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("impalaDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
*/


}
